/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package schtohan.restclient;

import java.util.ArrayList;
import java.util.Iterator;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import schtohan.business.Departure;

/**
 *
 * @author Schtohan
 */
@ManagedBean
@RequestScoped
public class VasttrafikBean {

    private DocumentBuilderFactory dfac;
    private DocumentBuilder dBuild;
    private ArrayList<Departure> departures;
    private VasttrafikClient client;
    
    private String stopName;
    private String nextDepTime;

    public VasttrafikBean() throws ParserConfigurationException {
        dfac = DocumentBuilderFactory.newInstance();
        dBuild = dfac.newDocumentBuilder();   
        departures = new ArrayList();
        client = new VasttrafikClient();
    }
    
    public String getStopName() {
        return stopName;
    }

    public void setStopName(String stopName) {
        this.stopName = stopName;
    }

    public String getNextDepTime() {
        return nextDepTime;
    }

    public void setNextDepTime(String nextDepTime) {
        this.nextDepTime = nextDepTime;
    }   
           
    public void getNextDep()
    {
        try
        {
            String stopId = getStopId(stopName);
            String depBoard = client.departureBoard(stopId, "1439");
            ObjectMapper mapper = new ObjectMapper();
            JsonNode root = mapper.readTree(depBoard);
            Iterator<JsonNode> depIterator = root.path("DepartureBoard").path("Departure").getElements();
            ArrayList<String> tidTabell = new ArrayList<String>();
            while(depIterator.hasNext())
            {
                JsonNode thisDep = depIterator.next();
                String linje = thisDep.path("name").getTextValue();
                if(linje.equals("Spårvagn 7"))
                {
                    tidTabell.add(thisDep.path("time").getTextValue());
                }     
            }
            
            nextDepTime = root.path("DepartureBoard").path("Departure").get(0).path("time").getTextValue();             
        }
        
        catch(Exception e) {}
    }
    
    private String getStopId(String stop)
    {
        try
        {
            //Hämta resultat för sökning på hållplats
            String locations = client.Location(stop);
            ObjectMapper mapper = new ObjectMapper();   
            JsonNode root = mapper.readTree(locations);
            JsonNode stops = root.path("LocationList").path("StopLocation");
            
            return stops.get(0).path("id").getTextValue();
        }
            
        catch(Exception e) {
            return null;
        }

    }

        
}
